package com.gui.textFields;

import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.JTextComponent;

/**
 * @author sad
 */
public class TextUtils {

    public static int getStartOfLine(JTextComponent component, int line) {
        Element root = component.getDocument().getDefaultRootElement();
        line = Math.max(line, 1);
        line = Math.min(line, root.getElementCount());
        int startOfLineOffset = root.getElement(line - 1).getStartOffset();
        return startOfLineOffset;
    }

    public static int getLineOfOffset(JTextComponent comp, int offset) {
        Document doc = comp.getDocument();
        if (offset < 0) {
            throw new RuntimeException("Can't translate offset to line");
        } else if (offset > doc.getLength()) {
            throw new RuntimeException("Can't translate offset to line");
        } else {
            Element map = doc.getDefaultRootElement();
            return map.getElementIndex(offset);
        }
    }
}
